package com.mz.ieann.aide.city.view

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Build
import android.view.MotionEvent
import android.view.View
import androidx.annotation.RequiresApi
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.mz.ieann.aide.R
import com.mz.ieann.aide.base.vm.BaseVMActivity
import com.mz.ieann.aide.city.adapter.CityLetterAdapter
import com.mz.ieann.aide.city.adapter.CityNameAdapter
import com.mz.ieann.aide.city.bean.City
import com.mz.ieann.aide.city.model.CityViewModel
import com.mz.ieann.aide.databinding.ActivityCityListLayoutBinding

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> 全国城市列表选择
 * <p>
 *
 * @author Created by Administrator
 * @date on 2021 2021/10/23 12:31
 */
class CityListActivity : BaseVMActivity<CityViewModel, ActivityCityListLayoutBinding>(R.layout.activity_city_list_layout) {

    /**
     * 城市列表
     */
    private var nameLayoutManger : GridLayoutManager? = null

    private var cityNameAdapter : CityNameAdapter? = null

    /**
     * 通知栏高度
     */
    private var statusBarHeight : Int = 0

    @RequiresApi(Build.VERSION_CODES.N)
    override fun initActivity() {
        getStatusBarHeight()

        viewModel.queryLetter()
        viewModel.letter.observe(this, {
            loadLetterAdapter(it)
        })

        viewModel.queryCity(this)
        viewModel.result.observe(this, {
            loadNameAdapter(it)
        })
    }

    private fun getStatusBarHeight(){
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0){
            statusBarHeight = resources.getDimensionPixelSize(resourceId)
        }
    }

    @SuppressLint("ClickableViewAccessibility")
    private fun loadLetterAdapter(letterList : ArrayList<City>){
        binding.cityLetterList.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        binding.cityLetterList.adapter = CityLetterAdapter(letterList)

        binding.cityLetterList.setOnTouchListener { _, event ->
            if (event.action == MotionEvent.ACTION_MOVE) {
                val view: View = binding.cityLetterList.findChildViewUnder(event.x, event.y)
                    ?: return@setOnTouchListener false
                val position: Int = binding.cityLetterList.getChildAdapterPosition(view)
                onLetterTouch(letterList[position].name)
            }
            false
        }
    }

    private fun loadNameAdapter(cityList : ArrayList<City>){
        nameLayoutManger = GridLayoutManager(this, 3)
        binding.cityNameList.layoutManager = nameLayoutManger
        cityNameAdapter = CityNameAdapter(cityList, binding.cityNameList)
        binding.cityNameList.adapter = cityNameAdapter
        onListener(cityList, nameLayoutManger)
    }

    fun onLetterClick(view : View){
        val letter = view.tag?.toString()
        cityNameAdapter?.getClickItemIndex(letter)?.let {
            scrollCity(letter, it)
        }
    }

    private fun onLetterTouch(letter : String){
        cityNameAdapter?.getClickItemIndex(letter)?.let {
            scrollCity(letter, it)
        }
    }

    fun onCityClick(view: View){
        val keyWord = binding.keywordSearch.text.toString()
        val intent = Intent(this, HouseListActivity::class.java)
        intent.putExtra("keyWord", keyWord)
        startActivity(intent)

    }

    private fun scrollCity(letter: String?, position : Int){
        nameLayoutManger?.scrollToPositionWithOffset(position, 0)
        binding.selectHide.text = letter
        binding.selectHide.visibility = View.VISIBLE
        binding.selectHide.postDelayed({
            binding.selectHide.visibility = View.GONE
        }, 3000)
    }

    fun onNameClick(view : View){
        view.tag?.let {
            binding.keywordSearch.setText(it.toString())
        }
    }

    private fun onListener(cityList : List<City>, nameLayoutManger : GridLayoutManager?){
        binding.cityNameList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                nameLayoutManger?.let {
                    val firstCompletePosition = it.findFirstCompletelyVisibleItemPosition()
                    val firstPosition = it.findFirstVisibleItemPosition()
                    val city = cityList[firstCompletePosition]
                    when{
                        dy == 0 || firstCompletePosition / it.spanCount == 0 -> {
                            binding.selectName.visibility = View.GONE
                            binding.selectName.text = ""
                        }
                        else -> {
                            binding.selectName.visibility = View.VISIBLE
                            binding.selectName.text = cityList[firstPosition].firstLetter
                            selectCityTransAnima(city, it.findViewByPosition(firstCompletePosition))
                        }
                    }
                }
            }
        })
    }

    private fun selectCityTransAnima(city : City, view : View?){
        val param = binding.spaceName.layoutParams as ConstraintLayout.LayoutParams
        when{
            city.isFirst -> {
                val location = IntArray(2)
                view?.getLocationOnScreen(location)
                param.topMargin = location[1] - statusBarHeight - this.resources.getDimensionPixelOffset(R.dimen.dp_60)
            }
            else -> {
                param.topMargin = this.resources.getDimensionPixelOffset(R.dimen.dp_40)
            }
        }
        binding.spaceName.layoutParams = param
    }

}